<template>
  <div class="panel">
    <van-nav-bar :title="title" right-text="保存" @click-right="onClickRight">
      <template #left>
        <van-icon @click="$router.go(-1)" name="arrow-left" />
      </template>
    </van-nav-bar>
    <van-form validate-first>
      <van-field
        name="text"
        placeholder="请输入内容"
        :rules="rules.code"
        v-model="value"
      />
    </van-form>
  </div>
</template>

<script>
// 导入Vuex中的数据
import { mapState, mapActions } from 'vuex'
// 导入接口
import { edit } from '@/api/my.js'
import { Toast } from 'vant'
export default {
  computed: {
    ...mapState({
      userInfo: state => state.userInfo
    })
  },
  // 利用jq来传参
  created () {
    if (this.$route.query.id === 'position') {
      this.title = '修改岗位'
      this.value = this.userInfo.position
    } else if (this.$route.query.id === 'nickname') {
      this.title = '修改个性签名'
      this.value = this.userInfo.nickname
    } else {
      this.title = '修改简历'
      this.value = this.userInfo.intro
    }
  },
  data () {
    return {
      // 标题
      title: '',
      // 输入框的内容
      value: '',
      // 提示用户不能为空
      rules: {
        code: [{ required: true, message: '请输入昵称', trigger: 'onBlur' }]
      }
    }
  },
  methods: {
    ...mapActions(['setUserInfo']),
    // 点击保存按钮
    async onClickRight () {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 20000
      })
      if (this.$route.query.id === 'position') {
        try {
          await edit({ position: this.value })
          // 提示修改成功
          Toast.success('修改成功')
        } catch {
          Toast.fail('修改失败')
        }
      } else if (this.$route.query.id === 'nickname') {
        try {
          await edit({ nickname: this.value })
          // 提示修改成功
          Toast.success('修改成功')
        } catch {
          Toast.fail('修改失败')
        }
      } else {
        try {
          await edit({ intro: this.value })
          // 提示修改成功
          Toast.success('修改成功')
        } catch {
          Toast.fail('修改失败')
        }
      }
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less" scoped>
.panel {
  /deep/.van-cell {
    width: 345px;
    margin: 10px auto;
    background: #f7f4f5;
  }
  /deep/.van-nav-bar__title {
    font-size: 16px;
    color: #fff;
  }
  /deep/.van-nav-bar__text {
    color: #fff;
  }
  /deep/.van-icon-arrow-left::before {
    color: #fff;
    font-size: 20px;
  }
  /deep/.van-nav-bar {
    background-color: #ca0131;
  }
}
</style>
